'use strict';

const Service = require('egg').Service;

module.exports = class SmilesService extends Service {
  // Update Smilies ///////////////////////////////////////////////////////////////////
  async updateSmilies() {
    const func = this.ctx.helper;
    const input = this.ctx.request.body;
    const connBlog = this.ctx.app.connBlog;

    // Update --------------------------------
    if (this.ctx.request.query.act === 'update') {
      const arrID = input.id.split(',');
      const arrCode = input.code.split(',');
      const arrImage = input.image.split(',');
      for (let i = 0; i < arrID.length; i++) {
        // Check data
        arrID[i] = func.checkInt(arrID[i]);
        arrCode[i] = func.trim(arrCode[i]);
        arrImage[i] = func.trim(arrImage[i]);
        if (arrCode[i].length < 1 || arrCode[i].length > 25) arrID[i] = -1;
        if (arrImage[i].length < 1 || arrImage[i].length > 50) arrID[i] = -1;

        // Update DB
        const arrData = { sm_code: arrCode[i],
          sm_image: arrImage[i] };
        if (arrID[i] != -1) {
          await connBlog.update('blog_smilies', arrData, 'sm_id=' + arrID[i]);
        }
        // Insert new smilies
        if (arrID[i] == 0) {
          await connBlog.insert('blog_smilies', arrData);
        }
      }
      return;
    }

    // Delete --------------------------------
    if (this.ctx.request.query.act === 'delete') {
      if (!input.selected) return;
      let arrSelected = input.selected.split(',');
      for (let i = 0; i < arrSelected.length; i++) {
        arrSelected[i] = func.checkInt(arrSelected[i]);
        if (arrSelected[i] < 1) {
          arrSelected.splice(i, 1);
          i--;
        }
      }
      if (arrSelected.length > 0) {
        arrSelected = arrSelected.join(',');
        await connBlog.doDelete('blog_smilies', 'sm_id IN (' + arrSelected + ')');
      }
      return;
    }

  }
}
